import json
import time
from threading import Thread

from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer


wss = []

class SimpleEcho(WebSocket):

    def handleMessage(self):
        if self.data is None:
            self.data = ''

    def handleConnected(self):
        print(self.address, 'connected')
        if self not in wss:
            wss.append(self)

    def handleClose(self):
         print(self.address, 'closed')


def postMessage(msg):
   try:
       for item in wss:
           print(type(item))
           item.sendMessage(msg)
   except Exception as e:
       print(msg+"&&&&"+str(e))



def startWbSocket():
    server = SimpleWebSocketServer('', 8000, SimpleEcho)
    server.serveforever()


def marketData2dict(pDepthMarketData):
    return {
        'InstrumentID': pDepthMarketData.InstrumentID,
        'TradingDay': pDepthMarketData.TradingDay,
        'ExchangeID': pDepthMarketData.ExchangeID,
        'BidPrice1':  pDepthMarketData.BidPrice1,
        'AskPrice1': pDepthMarketData.AskPrice1,
        'HighestPrice': pDepthMarketData.HighestPrice,
        'LowestPrice': pDepthMarketData.LowestPrice,
        'LastPrice': pDepthMarketData.LastPrice,
        'OpenPrice': pDepthMarketData.OpenPrice,
        'ClosePrice': pDepthMarketData.ClosePrice,
        'UpperLimitPrice': pDepthMarketData.UpperLimitPrice,
        'LowerLimitPrice': pDepthMarketData.LowerLimitPrice
    }






